<?php
include("../amazon_api_class.php");

class RetriveData
{
	function requestJournal($word)
	{
		$url = "http://www.questia.com/app/direct/SM.qst";
		$data = "formids=Hidden%2CIf%2CTextField%2Cbooks%2Cjournals%2Cmagazines%2Cnewspapers%2Cencyclopedia%2CIf_0&" . 
			"component=%24coreweb%24search%24components%24basicSearch_0.basicSearchForm&" . 
			"page=retail%2Fhome%2FhomePage&service=direct&session=T&" . 
			"submitmode=&submitname=&Hidden=T&If=F&If_0=T&TextField=" . urlencode($word) . "&" . 
			"books=on&journals=on&magazines=on&newspapers=on&encyclopedia=on";
			
		$params = array('http' => array(
			  'method' => 'POST',
			  'content' => $data
			));
		if ($optional_headers !== null) {
			$params['http']['header'] = $optional_headers;
		}
		$ctx = stream_context_create($params);
		$fp = @fopen($url, 'rb', false, $ctx);
		if (!$fp) {
			throw new Exception("Problem with $url, $php_errormsg");
		}
		$response = @stream_get_contents($fp);
		$response = utf8_encode($response);
		
		$result = array();
		
		if ($response === false) {
			throw new Exception("Problem reading data from $url, $php_errormsg");
		}
		else
		{
			$key = "<a href=\"#Journal\">";
			$posNumber1 = strpos($response, $key);			
			$key = "</a>";
			$posNumber2 = strpos($response, $key, $posNumber1);			
			$numJournal = strip_tags(substr($response, $posNumber1, $posNumber2 - $posNumber1));
			$numJournal = intval($numJournal);
			
			if ($numJournal > 0)
			{			
				$key = "id=\"resultsRowsJournal\"";
				$pos = strpos($response, $key, $posNumber2);		
				$key = "<a href=\"/PM";
				$pos = strpos($response, $key, $pos);			
				$key = ">";
				$pos1 = strpos($response, $key, $pos);			
				$key = "</a>";			
				$pos2 = strpos($response, $key, $pos1);			
				$titleOfArticle = trim(substr($response, $pos1 + 1, $pos2 - $pos1 - 1));
				
				$key = "Journal article by";
				$pos3 = strpos($response, $key, $pos2) + strlen($key);
				$key = "</div>";
				$pos4 = strpos($response, $key, $pos3);
				$data = substr($response, $pos3 + 1, $pos4 - $pos3 - 1);
				$data = strip_tags($data);
				
				$temp1 = explode(";", $data);
				$author = explode(" ", trim($temp1[0]));
				
				$firstName = "";
				$lastName = "";
				
				$firstName = $author[0];
				$lengthAuthor = count($author);
				if ($lengthAuthor > 1)
				{
					$lastName = $author[$lengthAuthor - 1];
				}
				
				$temp2 = explode(',', trim($temp1[1]));
				$lengthTemp2 = count($temp2);
				$titleOfJournal = trim($temp2[0]);
				$year = trim($temp2[$lengthTemp2 - 1]);
				
				$temp3 = explode(" ", trim($temp2[$lengthTemp2 - 2]));
				$volumnNumber = trim($temp3[1]);		
				
				//get suguestion link
								
				$result = array();		
				$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=%22" . urlencode($word) . "%22+filetype:pdf", true, $result, 1);
				$data = null;
		
				$result	 = array(
					firstName => $firstName,
					lastName => $lastName,
					titleOfArticle => $titleOfArticle,
					titleOfJournal => $titleOfJournal,
					volumeNumber => $volumnNumber,
					year => $year,
					suggues_link => count($result) > 0 ? $result[0] : null
				);
			}
		}
		
		return $result;
	}

	private function getGoogleLinks($url, $type, &$result = 1, $numberResult = 1)
	{
		$handle = fopen($url, "r");
		$content = "";		
		
		while (!feof($handle))
		{
			$content .= fgets($handle, 1000);				
		}
		fclose($handle);
		
		$content = utf8_encode($content);
		
		$currentPost = 0;				
		$keyFirst = "";
		if ($type == 1)
		{
			$keyFirst = "<div class=gs_rt>";
		}
		else if ($type == 2)
		{
			$keyFirst = "<h3 class=\"r\">";			
		}
		else if ($type == 3)
		{
			$keyFirst = "<h3 class=\"r\">";			
		}
				
		$found = 0;		
		while($found < $numberResult)
		{
			$key = $keyFirst;
			$pos1 = strpos($content, $key, $currentPost);			
			
			if (!$pos1)
			{
				break;
			}
			$key = "href=";
			$pos2 = strpos($content, $key, $pos1) + strlen($key) + 1;
			$key = "\"";
			$pos3 = strpos($content, $key, $pos2 + 1);			
			$link = substr($content, $pos2, $pos3 - $pos2);			
			$key = ">";
			$pos4 = strpos($content, $key, $pos3) + 1;
			$key = "</a>";
			$pos5 = strpos($content, $key, $pos4);
			$title = substr($content, $pos4, $pos5 - $pos4);
			$title = strip_tags($title);
			
			//change next position to search
			$currentPost = $pos5;
			
			$data = array($title, $link);
			array_push($result, $data);
			$found++;			
		}		
	}
	
	public function getSuggestionByComposeAssigmentTitle($title)
	{
		$title = urlencode($title);
		$result = array();	
		
		$data = $this->getGoogleLinks("http://www.google.com/search?q=wiki+%22" . $title . "%22+site:en.wikipedia.org&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);				
		$data = $this->getGoogleLinks("http://www.google.com/search?q=%22" . $title . "%22+site:edu+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 2);		
		$data = $this->getGoogleLinks("http://www.google.com/search?q=%22" . $title . "%22+site:edu.au+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);		
		$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=%22" . $title . "%22+filetype:pdf", 1, $result, 4);
		$result[] = array("", "");
		$data = $this->getGoogleLinks("http://www.google.com/search?q=critique+of+%22" . $title . "%22+site:edu+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);
		$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=critique+of+%22" . $title . "%22+filetype:pdf", 1, $result, 1);
		$data = $this->getGoogleLinks("http://www.google.com/search?q=re-thinking+%22" . $title . "%22+site:edu+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);
		$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=re-thinking+%22" . $title . "%22+filetype:pdf", 1, $result, 1);
		$data = $this->getGoogleLinks("http://www.google.com/search?q=reviewing+%22" . $title . "%22+site:edu+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);
		$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=reviewing+%22" . $title . "%22+filetype:pdf", 1, $result, 1);
		$data = $this->getGoogleLinks("http://www.google.com/search?q=anti-thesis+of+%22" . $title . "%22+site:edu+filetype:pdf&ie=utf-8&oe=utf-8&aq=t", 2, $result, 1);
		$data = $this->getGoogleLinks("http://scholar.google.com/scholar?q=anti-thesis+of+%22" . $title . "%22+filetype:pdf", 1, $result, 1);	
		
		return $result;
	}
	
	public function getGoogleBook($title)
	{
		$title = urlencode($title);
		$result = array();	
		
		$url = "http://www.google.com/search?q=" . $title . "&btnG=Search&tbm=bks&tbo=1&hl=vi&gbv=1&ei=7-TMTo24FcGXiQe-xPnADg";
		$data = $this->getGoogleLinks($url, 3, $result, 6);		
		
		return $result;
	}
	
	public function getBooksFromAmazon($title)
	{
		$arr = array();
		try
		{
			$obj = new AmazonProductAPI();
			$result = $obj->searchProducts($title,
											   AmazonProductAPI::DVD,
											   "TITLE",10);
			foreach ($result->Items->Item as $item)
			{
				$data = "";
				$data->title = $item->ItemAttributes->Title;
				$data->author = $item->ItemAttributes->author;
				$data->publisher = $item->ItemAttributes->Publisher;
				$data->ISBN = $item->ItemAttributes->ISBN;
				$data->datetime = strtotime($item->ItemAttributes->PublicationDate);
				$data->url = $item->DetailPageURL;
				$arr[] = $data;												
			}
			
			usort($arr, array("RetriveData", "sortDateAmazon"));
		}
		catch(Exception $e)
		{
			
		}
		return $arr;
	}
	
	public static function sortDateAmazon($a, $b)
	{
		return $a->datetime < $b->datetime;
	}
}

/*

$da = new RetriveData();
$arr = $da->getBooksFromAmazon("deconstruction");
for($i =0; $i < count($arr); $i++)
{
	echo $arr[$i]->datetime . "<br/>";
}

for($i =0; $i < count($arr); $i++)
{
	echo $arr[$i]->datetime . "ddd<br/>";
}
usort($arr, "sortDateAmazon");
for($i =0; $i < count($arr); $i++)
{
	echo $arr[$i]->datetime . "<br/>";
}
*/
?>